<?php
/**
 * Created by PhpStorm.
 * User: 叶子
 * Date: 2017/12/27
 * Time: 16:42
 */

namespace Home\Controller;

use Think\Page2;
use Vendor\Useragent;
use Vendor\Mobiledetect;
use EasyWeChat\Foundation\Application;
class ArticletemController extends ComController
{

    public function post_list(){
        $id = $_GET['id'];
        $prefix = C('DB_PREFIX');
        $category_db = M('category');
        $article_db = M("article as a");
        $photos_db = M(photos);
        $this->assign("onclassflag",$id);
        //post_list.html轮播图
        $articlebanner = $article_db
            ->where(array("sid"=>$id,"pushBanner"=>1))
            ->join("{$prefix}category ON {$prefix}category.id = a.sid")
            ->field("a.title,a.description,a.thumbnail,a.aid,a.link,a.sid,{$prefix}category.dir")
            ->limit(3)
            ->order("browse DESC")
            ->select();

        $this->assign("articlebanner",$articlebanner);
        $this->assign("articlebannerwap",$articlebanner);
        // 最近七天点击最多的栏目文章列表
        $hotListLog = $this->hotList($id);
        if(!empty($hotListLog)){
            foreach ($hotListLog as $key => $val){
                $hotList[$key]['title'] = $article_db->where("aid=".$val['aid'])->getField("title");
                $hotList[$key]['aid'] = $val['aid'];
                $hotList[$key]['dir'] =  $val['dir'];
            }
            $this->assign("hotList",$hotList);
        }

        //右侧广告图
        $rightAdvPic = $photos_db
            ->where(array("category"=>9))
            ->field("pic_url,link")
            ->select();
        $this->assign("rightAdvPic",$rightAdvPic['0']);

        //post_list.html body文章展示
        //分页
        $pagesize = 10;//每页数量
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $article_db->where(array("sid"=>$id))->count();
        $field = "a.aid,a.title,a.description,a.thumbnail,a.t,a.point,a.browse,{$prefix}category.name,{$prefix}category.dir";
        $list = $article_db
            ->where(array("sid"=>$id))
            ->field($field)
            ->order("aid desc")
            ->limit($offset . ',' . $pagesize)
            ->join("{$prefix}category ON {$prefix}category.id = a.sid")
            ->select();

        $dir=M("category")->where(array("id"=>$id))->getField("dir");
        $page = new Page2($count, $pagesize);
        $page->category = "/{$dir}-page";
        $page->url =   "/{$p}.html";
        $page = $page->show();
        for ($i= 0;$i<count($list);$i++){
            foreach ($list[$i] as $k=>$v){
                if($k == t){
                    $time = mdate(strtotime($v),now);
                    $list[$i]["time"] = $time;
                }
                if($k == description ) {
                    if (strlen($v) > 66) {
                        $list[$i]["description"] = mb_substr($v, 0, 66) . "...";
                    }
                }
            }
        }
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign(articlecon,$list);

        //导航栏
//        $categorycon= $category_db
//            ->field("id,name,dir")
//            ->select();
//        $this->assign(nav,$categorycon);
//        $this->assign(navp,$categorycon);
        //title
        $categorytit = $category_db
            ->field("name,dir")
            ->where(array("id"=>$id))
            ->select();
            
        $this->assign("columntit",$categorytit['0']['name']);
        $this->assign("dir",$categorytit['0']['dir']);
        // 微信浏览器
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            $config = [
                'app_id' => C("AppId"),
                'secret' => C("AppSecret"),
            ];
            $app = new Application($config);
            $js = $app->js;
            $this->assign('iswechat', 1);
            $this->assign('js', $js);
        }
        if(isMobile()){
            $this->display("Mobile/post_list");
        }else{
            $this->display();
        }
        
    }
    public function post_show(){
        $id = $_GET;
        $article_db = M("article as a");
        $photos_db = M("photos");
        $category_db = M("category");
        $comment_DB = M("Comment");
        // 记录访问信息
        $useAgent = new Useragent();
        // 来源搜索关键词
        $searchEngineData = get_search_engine_keyword($useAgent->referrer(), $useAgent->referrer());
        $referrer = strlen($useAgent->referrer()) > 255 ? substr($useAgent->referrer(), 0, 255) : $useAgent->referrer();
        $mobileDetect = new Mobiledetect ();
        // 浏览设备类型 1pc 2mobile 3table 9robot
        $broswerType = ($mobileDetect->isMobile() ? ($mobileDetect->isTablet() ? 3 : 2) : 1);
        if ($useAgent->is_robot) {
            // 机器人
            $broswerType = '9';
        }
        $sidSelect = M("article")->where(array("aid"=>$id["id"]))->field("sid")->select();
        $data = array(
            'aid'=>$id['id'],
            'sid'=>$sidSelect[0]['sid'],
            'ip_address' => get_client_ip(),
            'source_url' => $referrer,
            'platform_type' => $broswerType,
            'broswer'=>$useAgent->browser,
            'os_type' => $useAgent->platform,
            'keyword' => $searchEngineData['keywords'],
            'search_engin' => $searchEngineData['search_engine'],
            'visit_time'=>date("Y-m-d H:i:s",time()),
        );
        
        $browseFlag = M("visit_logs")->add($data);
        if(!empty($browseFlag)){
            //增加浏览量
            $articleBrowse_add  = $article_db
                ->where(array("aid"=>$id['id']))
                ->setInc('browse',1);
        }

        //文章列表
        $articlecon = $article_db
                    ->where(array("aid"=>$id['id']))
                    ->field("title,t,content,browse,point,aid,keywords,description,sid,thumbnail")
                    ->find();
        //print_r($articlecon);exit;
        $sid=$articlecon[0]['sid'];
        $dir=M("category")->field("dir")->where(array("id"=>$sid))->find();
        $time = mdate(strtotime($articlecon['t']),now);
        $content = $articlecon['content'];
        $contents = str_replace("img","mip-img",$content);
        $articlecon["time"] = $time;
        $this->assign("contents",$contents);
        $this->assign("dir",$dir['dir']);
        $this->assign("articlecon",$articlecon);
        $this->assign("titlecon",$articlecon['title']);
        if(strlen($articlecon['description'])>66){
            $this->assign("mateDes",mb_substr($articlecon['description'],0,66)."...");
        }else{
            $this->assign("mateDes",$articlecon['description']);
        }
        //右侧广告图
        $rightAdvPic = $photos_db
            ->where(array("category"=>9))
            ->field("pic_url,link")
            ->select();
        $this->assign("rightAdvPic",$rightAdvPic['0']);
        // 最近七天点击最多的栏目文章列表
        $sid = M("article")->where(array("aid"=>$id["id"]))->field("sid")->find();
        $hotListLog = $this->hotList($sid['sid']);
        if(!empty($hotListLog)){
            foreach ($hotListLog as $key => $val){
                $hotList[$key]['title'] = $article_db->where("aid=".$val['aid'])->getField("title");
                $hotList[$key]['aid'] = $val['aid'];
                $hotList[$key]['dir'] =  $val['dir'];
            }
            $this->assign("hotList",$hotList);
        }
        //导航栏
        $onclass = $article_db
                ->where(array("aid"=>$id['id']))
                ->field("sid")
                ->select();
        $this->assign("onclassflag",$onclass[0]['sid']);
        $categorycon= $category_db
            ->field("id,name,dir")
            ->select();
        $this->assign("nav",$categorycon);
        $this->assign("navp",$categorycon);
        //标签
        $labellist = M("adviser_product")->where(array("adviser_id"=>$id['id']))->field("pro_id")->select();
        $pro_listarr = array_column($labellist,'pro_id');
        for($i=0;$i<count($pro_listarr);$i++){
            $labels = M("adviser")->where(array("id"=>$pro_listarr[$i]))->field("name,id")->select();
            $labelli[$i]["name"]=$labels[0]['name'];
            $labelli[$i]["id"]=$labels[0]['id'];
        }
        $this->assign("labels",$labelli);//底部标签带可点击搜索
        //mate[keyword]显示本文标签
        for($ii=0;$ii<count($labelli);$ii++){
            $matekeyworw[$ii]=$labelli[$ii]["name"];
        }
        $matekeyworwstr = implode(",",$matekeyworw);
        $this->assign("matekeyw",$matekeyworwstr);
        //文章评论
        $comment_list = $comment_DB
            ->order("id DESC")
            ->select();
        foreach($comment_list as $v => $k){
            $comment_list[$v]["time"] = mdate(strtotime($comment_list[$v]["time"]),now);
        }
        $this->assign("commentList",$comment_list);
        // 微信浏览器
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            $config = [
                'app_id' => C("AppId"),
                'secret' => C("AppSecret"),
            ];
            $app = new Application($config);
            $js = $app->js;
            $this->assign('iswechat', 1);
            $this->assign('js', $js);
        }
        if(isMobile()){
            $this->display("Mobile/post_show");
        }else{
        $this->display();
        }
    }

    public function pointAdd(){
        //点赞
        $id = $_POST;
        $article_db = M("article");
        //dump($id);
        //echo($id['id']);
        $articlecon = $article_db
            ->where(array("aid"=>$id['id']))
            ->field("point")
            ->select();
        $articlePointadd = ++$articlecon['0']['point'];
        $articlePoint_add  = $article_db
            ->where(array("aid"=>$id['id']))
            ->setInc('point',1);
       $this->ajaxReturn($articlecon,"JSON");
    }


    public function search_by(){
        $category_db = M("category");
        $keyword = !empty($_GET['k']) ? $_GET['k'] : "";
        if(!empty($keyword)){
            $arr = $this->searchBy($keyword);
            if(!empty($arr)){
                if($arr['code']==400){
                    $this->assign("num",0);
                }else{
                    $this->assign("num",$arr["list"]["0"]['count']);
                }
                $this->assign('list',$arr['list']);
                $this->assign('page',$arr['page']);
                $this->assign('keyword',$keyword);
            }
            //导航栏

            $categorycon= $category_db
                ->field("id,name,dir")
                ->select();
            $this->assign("nav",$categorycon);
            $this->assign("navp",$categorycon);
            $this->assign("navi",$categorycon);
        }
        if(isMobile()){
            $this -> display("Mobile/searchby");
        }else{
            $this -> display("searchby");
        }
        
    }

    public function labelsearch($data){
        $datas = $data;
        $category_db = M("category");
        //dump($datas);
        if(!empty($datas['id'])){
            $arr = $this->searchLbP($datas['id']);
            if(!empty($arr)){
                if($arr['code']==400){
                    $this->assign("num",0);
                }else{
                    $this->assign("num",$arr["list"]["0"]['count']);
                }
                $this->assign("list",$arr['list']);
                $this->assign("page",$arr['page']);
                $this->assign("keyword",$datas['k']);
            }
        }
        //导航栏
        $categorycon= $category_db
            ->field("id,name,dir")
            ->select();
        $this->assign("nav",$categorycon);
        $this->assign("navp",$categorycon);
        $this->assign("navi",$categorycon);
        if(isMobile()){
            $this->display("Mobile/searchby");
        }else{
            $this->display("searchby");
        }
        
    }

    public function label(){
        //导航栏
        $category_db = M("category");
        $categorycon= $category_db
            ->field("id,name,dir")
            ->select();
        $this->assign("nav",$categorycon);
        $this->display();
    }
    public function tags(){
        $data = $_GET;
        if($data['id'] <> ''){
            $this->labelsearch($data);
        }else{
            //tags中的数据在Com控制器的_initialize中
                if(isMobile()){
                    $this->display("Mobile/tags");
                }else{$this->display();}
                
            
        }
    }
    //文章评论
    public function comment(){
        if(IS_POST && IS_AJAX){
            $comment_DB = M("Comment");
            $IP = $this->getIp();
            $aid = $_POST["id"];
            $content = $_POST["content"];
            $time = date("Y-m-d H:i:s",time());
            $data = array(
                "article_aid"    =>$aid,
                "user_ip"        =>$IP,
                "review_content" =>$content,
                "time"           =>$time
            );
           $add =$comment_DB->data($data)->add();
           if($add){
               $this->ajaxReturn('{"status":1,"msg":"评论成功"}');
           }else{
               $this->ajaxReturn('{"status":0,"msg":"评论失败"}');
           }
        }
    }





    /*-------------------------------------------*/
}